import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

import '../../blocs/order_detail.dart';
import '../../blocs/cart.dart';
import '../../util/app_util.dart';

import 'package:flutter_stripe_payment/flutter_stripe_payment.dart';

class OrderPaymentChannelPage extends StatefulWidget {
  const OrderPaymentChannelPage({Key? key}) : super(key: key);
  @override
  _OrderPaymentChannelPageState createState() => _OrderPaymentChannelPageState();
}

class _OrderPaymentChannelPageState extends State<OrderPaymentChannelPage> {
  final _stripePayment = FlutterStripePayment();

  @override
  void initState() {
    super.initState();
    stripeInit();
    // Provider.of<ProductDetail>(context, listen: false).fetchDetail(widget.product_id);
  }

  stripeInit() async {
    await _stripePayment.setStripeSettings(App3rdKey.stripe_key, App3rdKey.applepay_id);
    print(_stripePayment);
  }

  _callStripeDialog(BuildContext context, CartBloc ib_cart) async {
    var paymentResponse = await _stripePayment.addPaymentMethod();
    switch (paymentResponse.status) {
      case PaymentResponseStatus.succeeded:
        {
          print(paymentResponse.paymentMethodId);
          var lm_result = await AppSession.appUtil.paymentMaintain(paymentResponse.paymentMethodId!);
          if ((lm_result ?? {}).isNotEmpty) {
            // AppSession.stripePayMethodId = paymentResponse.paymentMethodId;
            AppSession.creditcard['pmid'] = paymentResponse.paymentMethodId;

            Map<String, dynamic> lm_param = {"payment_channel": 2};
            ib_cart.checkoutUpdate(lm_param);
          }
        }
        break;
      case PaymentResponseStatus.failed:
        {
          print(paymentResponse);
        }
        break;
      default:
        {
          print(paymentResponse);
        }
        break;
    }
  }

  List<Widget> list = List<Widget>.empty(growable :true);

  Map lm_payment_img = {
    2: {'img': 'payment_icon_credit.png', 'name': '信用卡'},
    11: {'img': 'payment_icon_alipay.png', 'name': '支付宝'},
    21: {
      'img': 'payment_icon_wechatpay.png',
      'name': '微信支付',
    },
  };

  @override
  Widget build(BuildContext context) {
    CartBloc _cart = Provider.of<CartBloc>(context, listen: false);

    return Scaffold(
      appBar: AppBar(
        brightness: Brightness.light,
        leading: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            child: Icon(
              Icons.chevron_left,
              color: AppColor.blackMain,
              size: 32,
            ),
          ),
        ),
        title: Text('支付方式', style: TextStyle(color: AppColor.blackMain)),
      ),
      body: SingleChildScrollView(
        child: Container(
          margin: EdgeInsets.only(top: 20.h),
          child: _channel_list(context, _cart),
        ),
      ),
    );
  }

  Widget _channel_list(BuildContext context, CartBloc ib_cart) {
    OrderDetailBloc _order_detail = Provider.of<OrderDetailBloc>(context, listen: false);
    list.clear();
    for (var lv_channel in ib_cart.ticket['available_payment_channels']) {
      list.add(GestureDetector(
        onTap: () async {
          if ((lv_channel['channel'] == 2) &&
              ((ib_cart.ticket['payment_cards']['2'] ?? {}).isEmpty)) {
            _callStripeDialog(context, ib_cart);
          } else {
            Map<String, dynamic> lm_param = {"payment_channel": lv_channel['channel']};
            await ib_cart.checkoutUpdate(lm_param);
            Navigator.pop(context);
          }
        },
        behavior: HitTestBehavior.opaque,
        child: ListTile(
          contentPadding: EdgeInsets.symmetric(horizontal: 26.w),
          leading: Image.asset(
            'assets/payment/' + lm_payment_img[lv_channel['channel']]['img'],
            width: 50.w,
            height: 34.h,
          ),
          title: Text(
            lm_payment_img[lv_channel['channel']]['name'],
            style: TextStyle(fontSize: 15.sp),
          ),
          trailing: Icon(Icons.chevron_right, size: 36),
        ),
      ));
    }
    return Column(children: list);
  }
}
